package pl.kosmowska.ewelina.client.views.impl;

import java.util.Date;
import java.util.List;

import pl.kosmowska.ewelina.client.Constants;
import pl.kosmowska.ewelina.client.ViewMessages;
import pl.kosmowska.ewelina.client.app.requestfactory.dto.OutcomeDataProxy;
import pl.kosmowska.ewelina.client.views.OutcomeView;
import pl.kosmowska.ewelina.client.views.widgets.MessageDialogBox;
import pl.kosmowska.ewelina.client.views.widgets.dialogs.BooleanDialog;
import pl.kosmowska.ewelina.client.views.widgets.dialogs.BooleanEvent;
import pl.kosmowska.ewelina.client.views.widgets.dialogs.BooleanEvent.Selected;
import pl.kosmowska.ewelina.client.views.widgets.dialogs.BooleanEventHandler;
import pl.kosmowska.ewelina.client.views.widgets.dialogs.OptionEvent;
import pl.kosmowska.ewelina.client.views.widgets.dialogs.OptionEventHandler;
import pl.kosmowska.ewelina.client.views.widgets.dialogs.ThreeOptionDialog;
import pl.kosmowska.ewelina.client.views.widgets.grids.OutcomeDataGrid;
import pl.kosmowska.ewelina.client.views.widgets.popup.PopupMessage;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.ResizeLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DateBox;

public class OutcomeViewImpl extends Composite implements OutcomeView {

	private static OutcomeViewImplUiBinder uiBinder = GWT
			.create(OutcomeViewImplUiBinder.class);

	@UiField
	DockLayoutPanel outcomeLayout;
	@UiField
	ResizeLayoutPanel outcomePanel;
	@UiField
	Button addOutcome;
	@UiField
	Button editOutcome;
	@UiField
	Button deleteOutcome;

	@UiField
	Button loadOutcomes;
	@UiField
	Panel startDatePanel;
	@UiField
	Panel endDatePanel;

	private BooleanDialog booleanDialog;
	private ThreeOptionDialog optionDialog;

	interface OutcomeViewImplUiBinder extends UiBinder<Widget, OutcomeViewImpl> {
	}

	private Presenter presenter;
	private boolean alreadyInit;

	private DateBox startDateBox = new DateBox();
	private DateBox endDateBox = new DateBox();
	private OutcomeDataGrid<OutcomeDataProxy> outcomeGrid;

	public OutcomeViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));
		startDatePanel.add(initDateBox(startDateBox, "Od: "));
		endDatePanel.add(initDateBox(endDateBox, "Do: "));
		outcomeGrid = new OutcomeDataGrid<OutcomeDataProxy>();

	}

	public HorizontalPanel initDateBox(DateBox dateBox, String name) {
		DateTimeFormat dateFormat = DateTimeFormat
				.getFormat(DateTimeFormat.PredefinedFormat.YEAR_MONTH_DAY);
		dateBox.setFormat(new DateBox.DefaultFormat(dateFormat));
		HorizontalPanel vPanel = new HorizontalPanel();
		vPanel.add(new HTML(name));
		vPanel.add(dateBox);
		return vPanel;
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public void reInitView(List<OutcomeDataProxy> returnedOutcomeData) {
		// debug
		System.out.println("OutcomeViewImpl.setLoggedIn(): Loading Outcome");
		outcomePanel.clear();
		reInitPagingDataGrid(returnedOutcomeData);
		outcomePanel.add(outcomeGrid);
	}

	@Override
	public void clearView() {
		outcomePanel.clear();
	}

	public void reInitPagingDataGrid(List<OutcomeDataProxy> returnedOutcomeData) {
		outcomeGrid = new OutcomeDataGrid<OutcomeDataProxy>();
		outcomeGrid.setHeight("800px");
		outcomeGrid.setWidth("100%");
		outcomeGrid.setDataList(returnedOutcomeData);
	}

	@UiHandler("deleteOutcome")
	void onDeleteOutcomeClick(ClickEvent event) {
		if (outcomeGrid.getSelectedItem() != null) {
			showDeleteConfirmationDialog();
		} else
			showMessage(ViewMessages.NOTHING_SELECTED_TO_DELETE);

	}

	@UiHandler("editOutcome")
	void onEditOutcomeClick(ClickEvent event) {
		if (outcomeGrid.getSelectedItem() != null) {
			presenter.goToOutcomeEditPlace(outcomeGrid.getSelectedItem());

		} else {
			showMessage(ViewMessages.NOTHING_SELECTED_TO_EDIT);
		}

	}

	@UiHandler("addOutcome")
	void onAddOutcomeClick(ClickEvent event) {
		presenter.goToNewOutcomePlace();
	}

	private void showDeleteConfirmationDialog() {
		if (outcomeGrid.getSelectedItem().getCategory()
				.equals(Constants.SAVINGS_CATEGORY)) {
			initDeleteSavingsBooleanDialog();
		} else if (!outcomeGrid.getSelectedItem().isMultiple()) {
			initBooleanDialog();
		} else {
			initDeleteOptionDialog();
		}
	}

	public void updateGrid(List<OutcomeDataProxy> toRemoveList,
			List<OutcomeDataProxy> toAddList) {
		outcomeGrid.removeFromDataList(toRemoveList);
		outcomeGrid.getDataList().addAll(toAddList);
		outcomeGrid.getDataProvider().refresh();
	}

	private void initDeleteSavingsBooleanDialog() {
		if (booleanDialog == null) {
			booleanDialog = new BooleanDialog(
					ViewMessages.CONFIRM_DELETE_SAVINGS_PART);
			booleanDialog.addSelectionHandler(new BooleanEventHandler() {
				public void onBooleanEvent(BooleanEvent event) {
					if (event.getBooleanEvent() == Selected.TRUE) {
						presenter.reInitSavingsPlan(outcomeGrid
								.getSelectedItem());
					} else if (event.getBooleanEvent() == Selected.FALSE) {
						// do nothing
					}
				}
			});
		}
		booleanDialog.center();
	}

	private void initBooleanDialog() {
		if (booleanDialog == null) {
			booleanDialog = new BooleanDialog(ViewMessages.CONFIRM_DELETE);
			booleanDialog.addSelectionHandler(new BooleanEventHandler() {
				public void onBooleanEvent(BooleanEvent event) {
					if (event.getBooleanEvent() == Selected.TRUE) {
						if (outcomeGrid.getSelectedItem().getSponsorKey() != null)
							presenter.deleteSavingsPlan(outcomeGrid
									.getSelectedItem().getSponsorKey());
						presenter.deleteSingleOutcome(outcomeGrid
								.getSelectedItem());
					} else if (event.getBooleanEvent() == Selected.FALSE) {
						// do nothing
					}
				}
			});
		}
		booleanDialog.center();
	}

	private void initDeleteOptionDialog() {
		if (optionDialog == null) {
			optionDialog = new ThreeOptionDialog(
					ViewMessages.SAVINGS_DELETE_OPTIONS_ENTRY);
			optionDialog.setOptionsText(ViewMessages.SAVINGS_DELETE_OPTIONS_1,
					ViewMessages.SAVINGS_DELETE_OPTIONS_2,
					ViewMessages.SAVINGS_DELETE_OPTIONS_3);
			optionDialog.addSelectionHandler(new OptionEventHandler() {
				public void onOptionEvent(OptionEvent event) {
					if (event.getOptionEvent() == OptionEvent.Selected.OPTION_1) {
						presenter.deleteSingleOutcome(outcomeGrid
								.getSelectedItem());
					} else if (event.getOptionEvent() == OptionEvent.Selected.OPTION_2) {
						presenter.deleteAllMultipleOutcome(outcomeGrid
								.getSelectedItem());
					} else if (event.getOptionEvent() == OptionEvent.Selected.OPTION_3) {
						presenter.deleteFollowingMultipleOutcome(outcomeGrid
								.getSelectedItem());
					} else if (event.getOptionEvent() == OptionEvent.Selected.FALSE) {
						// do nothing
					}
				}
			});
		}
		optionDialog.center();
	}

	@UiHandler("loadOutcomes")
	void onLoadOutcomesClick(ClickEvent event) {
		Date startDate = startDateBox.getValue();
		Date endDate = endDateBox.getValue();
		if (startDate == null || endDate == null) {
			showMessage(ViewMessages.ERROR_NO_DATES);
			return;
		} else if (startDate.getTime() > endDate.getTime()) {
			showMessage(ViewMessages.ERROR_WRONG_DATES);
			return;
		}

		java.sql.Date sqlDate1 = new java.sql.Date(startDate.getTime());
		java.sql.Date sqlDate2 = new java.sql.Date(endDate.getTime());

		presenter.loadDataForOutcomeView(sqlDate1, sqlDate2);

	}

	@Override
	public void showMessage(String message) {
//		MessageDialogBox messageDialogBox = new MessageDialogBox(message);
//		messageDialogBox.center();
//		messageDialogBox.show();
		
        final PopupMessage alertMessage = new PopupMessage(message);
        alertMessage.startProcessing();
        Timer t = new Timer() {
            public void run() {
                alertMessage.stopProcessing();
            }
        };
        t.schedule(1000);
	}
	


	@Override
	public void updateAfterOutcomeDelete(OutcomeDataProxy outcomeDataProxy) {
		outcomeGrid.removeFromDataList(outcomeDataProxy);
	}

	@Override
	public void updateAfterOutcomeDelete(List<OutcomeDataProxy> deletedList) {
		outcomeGrid.removeFromDataList(deletedList);
	}

	@Override
	public boolean isAlreadyInit() {
		return alreadyInit;
	}

	@Override
	public void setAlreadyInit(boolean alreadyInit) {
		this.alreadyInit = alreadyInit;
	}

}
